/**
 * User: Oleksii Savchenko
 * Date: 25.01.13
 * Time: 10:33
 */
var ajax = {
    /**
     * Options:
     *
     * url {String} - URL to make request
     * data {Object|Array} - data which we send to server
     * params {Object} - query parameters
     *
     */

    /**
     * Get information from server
     * @param {Object} options
     * @param {Function} callback
     */
    get: function(options, callback, params){
        this._ajaxRequest(options, callback, 'GET', params);
    },

    /**
     * Create data on the server
     * @param {Object} options
     * @param {Function} callback
     */
    create: function(options, callback){
        this._ajaxRequest(options, callback, 'POST');
    },

    /**
     * Update data on server
     * @param option
     * @param callback
     */
    update: function(options, callback, params) {
        this._ajaxRequest(options, callback, 'PUT', params);
    },

    /**
     * Remove data on server
     * @param option
     * @param callback
     */
    remove : function(options, callback, params){
        this._ajaxRequest(options, callback, 'DELETE', params);
    },

    _ajaxRequest: function(options, callback, request_method, params){
        var request = this._wrapXhr(window.XMLHttpRequest);

        var Url = params ? options.url + '?' + params : options.url;

        request.open(request_method, Url);
        request.onreadystatechange = function() {
            if(request.readyState === 4 && request.status === 200){
                var type = request.getResponseHeader('Content-Type');
                if(type.match(/^application/)){
                    callback(JSON.parse(request.responseText));
                } else if (type.match(/^text/)){
                    callback(request.responseText);
                }
            }
        };
        request.setRequestHeader('Content-Type', 'application/json');
        request.send(JSON.stringify(options.data));
    },

    /**
     * Get XMLHttpRequest for all browsers
     * Patch for IE 5 & IE6
     * @return {XMLHttpRequest}
     * @private
     */
    _wrapXhr: function(xhr){
        if(xhr === undefined){
                try{
                    // Use last version ActiveX object
                    return new ActiveXObject('Msxm12.XMLHTTP.6.0');
                } catch (e1){
                    try {
                        // Use old version
                        return new ActiveXObject('Msxm12.XMLHTTP.3.0');
                    } catch (e2){
                        // If all else fails create error
                        throw new Error('XMLHttpRequest not supported')
                    }
                }
        } else {
            return new XMLHttpRequest();
        }
    }

};